<template>
  <div class="page-container">
    <div class="table-wrap" v-loading="loading">
      <div class="search_header">
        <div class="search_header_left">
          <!-- 不需要新增按钮 -->
        </div>

        <div class="search_header_right">
          <el-date-picker
            @change="search"
            v-model="parameter.year"
            type="year"
            placeholder="年度"
            value-format="yyyy"
            :clearable="false"
            @clear="search"
            :picker-options="pickerOptions"
          />
        </div>
      </div>

      <div class="table-section">
        <el-table
          :data="yearList"
          class="year-table"
          :header-cell-style="{
            background: '#F2F6FB',
            color: ' #6B767D'
          }"
          height="100%"
        >
          <el-table-column
            label="主体名称"
            prop="name"
            show-overflow-tooltip
            width="140"
          >
            <!-- <template slot-scope="scope">
              <el-select
                placeholder="年度"
                v-model="scope.row.year"
              >
                <el-option
                  v-for="item in yearOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                  :disabled="
                    isOptionDisabledYear(item, scope.row)
                  "
                >
                </el-option>
              </el-select>
            </template> -->
          </el-table-column>
          <el-table-column
            label="本年度计划完成固投(万元)"
            prop="fixedTotal"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedTotal"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="1月"
            prop="fixedOneFirst"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedOneFirst"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="2月"
            prop="fixedOneSecond"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedOneSecond"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="3月"
            prop="fixedOne"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedOne"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="4月"
            prop="fixedTwoFirst"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedTwoFirst"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="5月"
            prop="fixedTwoSecond"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedTwoSecond"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="6月"
            prop="fixedTwo"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedTwo"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="7月"
            prop="fixedThreeFirst"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedThreeFirst"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="8月"
            prop="fixedThreeSecond"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedThreeSecond"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="9月"
            prop="fixedThree"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedThree"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="10月"
            prop="fixed_four_first"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedFourFirst"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="11月"
            prop="fixed_four_second"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedFourSecond"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="12月"
            prop="fixedFour"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedFour"
                type="number"
              />
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-button
                @click="deleteYearPlan(scope.$index)"
                type="text"
                style="color: #ff5b5b; font-weight: 400"
                >删除
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
    </div>

    <!-- 固定底部的保存按钮 -->
    <div class="line">
      <el-button
        type="primary"
        @click="saveData"
        :loading="saveLoading"
        class="save-btn"
        >保存
      </el-button>
    </div>
  </div>
</template>

<script>
import {
  queryInvestYearPlan,
  addOrUpdateInvestYearPlan
} from '@/api/investYearPlan'
import listKeepAliveMixin from '@/mixins/listKeepAliveMixin'
import { isAfterMonth } from '@/utils/datetime'

export default {
  name: 'investYearPlanList',
  mixins: [listKeepAliveMixin],
  data() {
    return {
      loading: false,
      saveLoading: false,
      parameter: {
        pageIndex: 1,
        pageSize: 10,
        year: ''
      },
      yearList: [],
      yearOptions: [],
      pickerOptions: {
        disabledDate: (date) => {
          return isAfterMonth(date, new Date())
        }
      }
    }
  },
  // created() {
  //   this.initYearOptions()
  //   this.getList()
  // },
  activated() {
    this.parameter.year = new Date()
      .getFullYear()
      .toString()
    this.getList()
  },
  methods: {
    // 初始化年份选项
    initYearOptions() {
      const currentYear = new Date().getFullYear()
      this.yearOptions = Array.from(
        { length: 5 },
        (_, i) => currentYear - 4 + i
      ).sort((a, b) => b - a)
    },
    // 搜索
    search() {
      this.getList()
    },
    // 获取列表数据
    async getList() {
      // if (!this.parameter.year) return
      this.loading = true
      try {
        const response = await queryInvestYearPlan({
          year: this.parameter.year
        })

        if (response.success) {
          this.processListData(response.data)
        } else {
          this.$message.error(
            response.message || '获取数据失败'
          )
        }
      } catch (error) {
        this.$message.error('获取数据失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    // 处理列表数据
    processListData(data) {
      this.yearList = []
      if (data.length) {
        data.forEach((item) => {
          const yearData = {
            pkid: item.pkid,
            year: item.year,
            unitId: item.unitId,
            name: item.name,
            fixedTotal: item.fixedTotal,
            fixedOne: item.fixedOne,
            fixedTwo: item.fixedTwo,
            fixedThree: item.fixedThree,
            fixedFour: item.fixedFour,
            fixedOneFirst: item.fixedOneFirst,
            fixedOneSecond: item.fixedOneSecond,
            fixedTwoFirst: item.fixedTwoFirst,
            fixedTwoSecond: item.fixedTwoSecond,
            fixedThreeFirst: item.fixedThreeFirst,
            fixedThreeSecond: item.fixedThreeSecond,
            fixedFourFirst: item.fixedFourFirst,
            fixedFourSecond: item.fixedFourSecond
          }

          // 检查除年份外的数据是否有非空值（包括0）
          // const hasYearData = [
          //   item.fixedTotal,
          //   item.fixedOne,
          //   item.fixedTwo,
          //   item.fixedThree,
          //   item.fixedFour,
          //   item.fixedOneFirst,
          //   item.fixedOneSecond,
          //   item.fixedTwoFirst,
          //   item.fixedTwoSecond,
          //   item.fixedThreeFirst,
          //   item.fixedThreeSecond,
          //   item.fixedFourFirst,
          //   item.fixedFourSecond
          // ].some(
          //   (value) =>
          //     value !== null &&
          //     value !== undefined &&
          //     value !== ''
          // )

          if (item.year) {
            this.yearList.push(yearData)
          }
        })
      }
    },
    // 年份选项禁用逻辑
    isOptionDisabledYear(optionValue, currentRow) {
      const selectedYears = this.yearList
        .filter((row) => row !== currentRow)
        .map((row) => row.year)
        .filter(Boolean)

      return selectedYears.includes(optionValue)
    },
    // 删除年度计划
    deleteYearPlan(index) {
      this.$confirm('确定删除这条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.yearList.splice(index, 1)
          this.$message.success('删除成功')
        })
        .catch(() => {})
    },
    // 保存数据
    async saveData() {
      // 数据验证
      for (let i = 0; i < this.yearList.length; i++) {
        const item = this.yearList[i]
        if (!item.year) {
          this.$message.error(`第${i + 1}行年度不能为空`)
          return
        }
      }

      this.saveLoading = true
      try {
        // 转换数据格式
        const saveData = this.yearList

        const response = await addOrUpdateInvestYearPlan(
          saveData
        )

        if (response.success) {
          this.$message.success('保存成功')
          this.getList() // 重新获取数据
        } else {
          this.$message.error(
            response.data?.message || '保存失败'
          )
        }
      } catch (error) {
        this.$message.error('保存失败')
        console.error(error)
      } finally {
        this.saveLoading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import '~@/assets/css/table.scss';

.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px 10px;
}

.table-wrap {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
}

.table-section {
  flex: 1;
  overflow: hidden;
}

.table-section ::v-deep .el-table__body-wrapper {
  overflow-y: auto !important;
}

.line {
  position: sticky;
  bottom: 0;
  width: calc(100% - 40px);
  margin: 0 auto;
  background: #fff;
  border-top: 1px solid #eee;
  padding: 10px 0;
  display: flex;
  justify-content: center;
  z-index: 10;
}

.save-btn {
  background: #497fa3;
  border: 1px solid #497fa3;
  width: 120px;
  height: 40px;
  color: white;
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.save-button-wrapper {
  margin-top: 20px;
  text-align: center;

  .el-button {
    width: 120px;
    height: 40px;
  }
}

.month-input-wrapper {
  width: 100%;
}
</style>
